package IEFYP.JunkCallFiltering;



import java.util.ArrayList;  
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.AdapterView;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import IEFYP.JunkCallFiltering.MyAdapter;
import IEFYP.JunkCallFiltering.DBhelper;

/**
 * 	*1. performance about large number of data!!!!<!!!<!!<!<!<
 * 	2.Select Blacklist V
 *  3.
 * 
 * @author KOLee
 *
 */


public class BlacklistController extends Activity {
	private ListView blacklist;
	private Spinner spn_type;
	private Button select_all;
	private EditText search_form;
	private Button update;
	private DBhelper b_data;
	private Button search;

	
	
    private MyAdapter listItemAdapter ;
    private MyAdapter C_List;
    
    public final static String TYPE = "type";  
    public final static String CALL_NO = "callno"; 
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blacklist);
        findView();
        setListView();
        setSpinner();
        setOnClickListener();
       
    }
    
    private void findView(){
    	blacklist = (ListView) findViewById(R.id.blacklist);
    	spn_type = (Spinner) findViewById(R.id.spn_type);
    	select_all = (Button) findViewById(R.id.select_all);
    	search_form = (EditText) findViewById(R.id.form);
    	update= (Button) findViewById(R.id.update);
    	search= (Button) findViewById(R.id.search);
    }
    
    private void setOnClickListener(){
   	 select_all.setOnClickListener(selectAll);
   	 search_form.setOnClickListener(searchForm);
   	 update.setOnClickListener(updateBlacklist);
   	 search.setOnClickListener(search_no);
   	 search_form.setOnKeyListener(onKey);
   }
    
    private OnKeyListener onKey = new OnKeyListener(){

		@Override
		public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
			 b_data = new DBhelper(BlacklistController.this,"blacklist");//@@@@@@@@@@@@@@@@@@@@@@@not sure
        	 b_data.OpenDB();//@@@@@@@@@@@@@@@@@@@@@@@not sure
			
        	 
        	 // TODO Auto-generated method stub
        	 
        	 String number = search_form.getText().toString();
			 C_List = listItemAdapter.clone();
      		 C_List.getList().clear();
      		 
      		 int pos_n=0;//@@@@@@@@@@@@@@@@@@@@@@@not sure
      		 for(Map<String,String> a: listItemAdapter.getList()){
      			 if(a.get(CALL_NO).startsWith(number)){
      				 C_List.getList().add(a);
      				 C_List.map.put(pos_n, b_data.checkBlocked(a.get(CALL_NO))); //@@@@@@@@@@@@@@@@@@@@@@@not sure  
      				 Log.e("1 "," add" );
      				 pos_n++;//@@@@@@@@@@@@@@@@@@@@@@@not sure  
      			 }
      		 }
      		 if(C_List.getList().isEmpty()){
      			HashMap<String,String> a = new HashMap<String, String>();
      			a.put(CALL_NO, "No Recorded");
      		    C_List.getList().add(a);
      		 }
      		 blacklist.setAdapter(C_List);
      		 
      		 
      		 Log.e("1 "," enter" );
      		 b_data.close();//@@@@@@@@@@@@@@@@@@@@@@@not sure
			return false;
		}
    	
    };
    
    
    private OnClickListener updateBlacklist = new OnClickListener(){
    	 public void onClick(View v){

    	 }
    };
    
  
    
    private OnClickListener search_no = new OnClickListener(){
	   	 public void onClick(View v){
	   		 
	   		 b_data = new DBhelper(BlacklistController.this,"blacklist");//@@@@@@@@@@@@@@@@@@@@@@@not sure
        	 b_data.OpenDB();//@@@@@@@@@@@@@@@@@@@@@@@not sure
        	 int pos_n=0;//@@@@@@@@@@@@@@@@@@@@@@@not sure
        	 
	   		String number = search_form.getText().toString();
			 C_List = listItemAdapter.clone();
       		 C_List.getList().clear();
       		 for(Map<String,String> a: listItemAdapter.getList()){
       			 if(a.get(CALL_NO).startsWith(number)){
       				 C_List.getList().add(a);
       				 C_List.map.put(pos_n, b_data.checkBlocked(a.get(CALL_NO))); //@@@@@@@@@@@@@@@@@@@@@@@not sure  
       				 Log.e("1 "," add" );
       				pos_n++;//@@@@@@@@@@@@@@@@@@@@@@@not sure  
       			 }
       		 }
       		 if(C_List.getList().isEmpty()){
       			HashMap<String,String> a = new HashMap<String, String>();
       			a.put(CALL_NO, "No Recorded");
       		    C_List.getList().add(a);
       		 }
       		 blacklist.setAdapter(C_List);
       		 Log.e("1 "," enter" );
       		 b_data.close();//@@@@@@@@@@@@@@@@@@@@@@@not sure
				
			
	   	 }
   };
    
    private OnClickListener searchForm = new OnClickListener(){
    	 public void onClick(View v){
    		 String text = "";
    		 search_form.setText(text);   		 
    	 }

    };
       
    
    //*************************Select all********************************// Still have problem !!!!!
    
   private OnClickListener selectAll = new OnClickListener(){
 
	public void onClick(View v)  // the mapping should base on the database
        {	
	//	C_List  = (MyAdapter) blacklist.getAdapter();
   		 b_data = new DBhelper(BlacklistController.this,"blacklist");
   		 b_data.OpenDB();
   		//String callno = ((Map<String,String>)a.getItem(1)).get(CALL_NO);
   		//AbsoluteLayout l = (AbsoluteLayout) va;
   		//TextView t = (TextView) l.getChildAt(0);
   		//Toast.makeText(BlacklistController.this, "You selected Item "+ callno,500).show();  
   		 
   		 
   		boolean Allchecked = C_List.checkSelected();//depend on MyAdapter.ALLchecked
   		
   		for(int i=0; i <C_List.getCount() ;i++){
   			if(Allchecked){	
   				C_List.map.put(i, false);      			
   				
   	          b_data.update((String) C_List.getList().get(i).get(CALL_NO), "isblocked", false);            	
   			}else{
   				C_List.map.put(i, true);  		 			 
  	          b_data.update((String) C_List.getList().get(i).get(CALL_NO), "isblocked", true);
   			}  				
   		 }
   		// Allchecked = !Allchecked;
   		 blacklist.setAdapter(C_List);
   		 b_data.close();		 
        }
   };
   
    private void setListView(){
    	
    	ArrayList<Map<String,String>> ListItem = new ArrayList<Map<String, String>>();
    	
    	b_data = new DBhelper(BlacklistController.this,"blacklist");
    	b_data.OpenDB();
        Cursor b_cursor = b_data.loadAll();
        List<Integer> list = new ArrayList<Integer>();
      
        if(b_cursor.moveToFirst()){
        	  int callnocol = b_cursor.getColumnIndex("call_no");
              int typecol = b_cursor.getColumnIndex("type");
              int isblockcol = b_cursor.getColumnIndex("isblocked");
  
        	
        	do{      	
        		HashMap<String,String> map = new HashMap<String, String>();
        		
        		Resources res=getBaseContext().getResources();
        		String[] types = res.getStringArray(R.array.types);
        		
        		map.put(CALL_NO,b_cursor.getString(callnocol));
        		map.put(TYPE,types[Integer.parseInt(b_cursor.getString(typecol))]);
        		list.add(b_cursor.getInt(isblockcol));
        		ListItem.add(map);   
        		
        		
        	}while(b_cursor.moveToNext());        	
        
        
        b_data.close();
        
    	
    	//Log.e(this.toString(), "error:2");
    	listItemAdapter = new MyAdapter(BlacklistController.this,ListItem,
    			R.layout.blacklistcontent,
    			new String[]{CALL_NO,TYPE},
    			new int[]{R.id.callno,R.id.type},
    			true  //initial value of check box
    	);
    	//Log.e(this.toString(), "error:3 ");
    	C_List = listItemAdapter.clone();
    	blacklist.setAdapter(listItemAdapter);
 

        }else{
		List<Map<String, String>> List = new ArrayList<Map<String,String>>();
		HashMap<String,String> mapping = new HashMap<String, String>();
		mapping.put("Notice","No Records");
		List.add(mapping);
		SimpleAdapter  adapter = new SimpleAdapter(this,List,
			R.layout.norecords,
			new String[]{"Notice"},
			new int[]{R.id.no_records});
			blacklist.setAdapter(adapter);
        }
    	
        /************initilizse the blacklist***********************/
         C_List  = (MyAdapter) blacklist.getAdapter();
   		for(int i=0; i <C_List.getCount() ;i++){
   			if(list.get(i)==1){	
   				C_List.map.put(i, true);   				
   			}else{
   				C_List.map.put(i, false);  			
   			}  				
   		 }
   		 blacklist.setAdapter(C_List);
   		/************initilizse the blacklist***********************/
   		 
   		 
        
        blacklist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<? > parent, View view, int position, long id) {      
            	
            	  CheckBox checkBox = (CheckBox) view.findViewById(R.id.b_select);                 
                  checkBox.toggle();
                  listItemAdapter .map.put(position, checkBox.isChecked());
                  
                   AbsoluteLayout lr=(AbsoluteLayout)view;
                   TextView mText=(TextView)lr.getChildAt(1);
                                
              	  b_data = new DBhelper(BlacklistController.this,"blacklist");
            	  b_data.OpenDB();
                  b_data.update(mText.getText().toString(), "isblocked", checkBox.isChecked());
                  b_data.close();
                  
                  
                // TODO Auto-generated method stub 
            //    AbsoluteLayout lr=(AbsoluteLayout)view;
            //   TextView mText=(TextView)lr.getChildAt(1);
               //CheckBox cb = (CheckBox) lr.getChildAt(2);

              //  Toast.makeText(BlacklistController.this, "You selected Item NO."+ position+"\nCall No.:"+mText.getText().toString(),//+"\n"+cb.toString(),
              //          500).show();                  
            }
           });
        
        
        
    	

  
    }   
    
    private void setSpinner(){
        Resources res=getBaseContext().getResources();
        String[] types = res.getStringArray(R.array.types);
    	
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,types);
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	spn_type.setAdapter(adapter);
    	
    	spn_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView adapterView, View view, int position, long id){
                //Toast.makeText(BlacklistController.this, "You selected"+adapterView.getLastVisiblePosition(), Toast.LENGTH_LONG).show();
            	Resources res=getBaseContext().getResources();
            	String[] types = res.getStringArray(R.array.types); 
            			
            	 b_data = new DBhelper(BlacklistController.this,"blacklist");//@@@@@@@@@@@@@@@@@@@@@@@not sure
            	 b_data.OpenDB();//@@@@@@@@@@@@@@@@@@@@@@@not sure

                          			
            			if(position!=0){
            		
            				 int pos_n=0;//@@@@@@@@@@@@@@@@@@@@@@@not sure
            				 C_List = listItemAdapter.clone();
    	            		 C_List.getList().clear();
    	            		 for(Map<String,String> a: listItemAdapter.getList()){
    	            			 if(a.get(TYPE).contentEquals(types[position])){ // types[position] : the types in strings form
    	            				 C_List.getList().add(a);
    	            				 C_List.map.put(pos_n, b_data.checkBlocked(a.get(CALL_NO)));   //@@@@@@@@@@@@@@@@@@@@@@@not sure
    	            				 Log.e("1 "," add" );
    	            				 pos_n++; //@@@@@@@@@@@@@@@@@@@@@@@not sure
    	            			 }
    	            			
    	            		 }
    	            		 
    	            		 blacklist.setAdapter(C_List);
    	            		 Log.e("1 "," enter" );
            			}
            			                       
                b_data.close();//@@@@@@@@@@@@@@@@@@@@@@@not sure
                   		
            			
	            		       	
            }
            
            
            public void onNothingSelected(AdapterView arg0) {
                Toast.makeText(BlacklistController.this, "No Selection", Toast.LENGTH_LONG).show();
            }
           
        });
         
    }
    
        
}
